package main

import (
	"english/common"
	"english/word"
	"github.com/gizak/termui/v3"
	"github.com/gizak/termui/v3/widgets"
	"log"
	"strings"
)

var currentCMD string
var currentContent *word.Content
var currentMod string
var contents *widgets.Paragraph
var data []string

func init() {
	currentMod = "w"
}

func main() {
	assist()
	echoHelp()
}

func addContent(content string)  {
	data = append(data, content)
	contents.Text = strings.Join(data, "\n")
	termui.Render(contents)
}

func clear() {
	data = []string{}
	contents.Text = strings.Join(data, "\n")
	termui.Render(contents)
}

func assist()  {
	if err := termui.Init(); err != nil {
		log.Fatalf("failed to initialize termui: %v", err)
	}
	defer termui.Close()

	contents = widgets.NewParagraph()
	contents.SetRect(0, 0, 60, 100)
	contents.Border = false
	contents.WrapText = true
	contents.TextStyle = termui.NewStyle(termui.ColorCyan)
	termui.Render(contents)

	for e := range termui.PollEvents() {
		if e.Type == termui.KeyboardEvent {
			if e.ID == "n" || e.ID == "<Space>" {
				switchCmd("n")
			} else if e.ID == "c" {
				switchCmd("c")
			} else if e.ID == "d" {
				switchCmd("d")
			} else if e.ID == "t" {
				switchCmd("t")
			} else if e.ID == "h" {
				switchCmd("h")
			} else if e.ID == "r" {
				switchCmd("r")
			} else if e.ID == "s" {
				switchCmd("s")
			} else if e.ID == "w" {
				switchCmd("w")
			} else if e.ID == "m" {
				switchCmd("m")
			} else if e.ID == "<C-c>" {
				switchCmd("gc")
			} else if e.ID == "<C-e>" {
				switchCmd("ge")
			} else if e.ID == "<Escape>" {
				return
			}
		}
	}
}

func echoHelp() {
	addContent(">>> Esc【退出】 r【阅读模式】  ctrl+c【猜中文】  ctrl+e【猜英文】  n/空格【下一个】 s【句子】 w【单词】 t【翻译】 c【清屏】 d【伪装】<<<")
}

func switchCmd(cmd string)  {

	if cmd == "n" {
		currentContent = word.GetContent(currentMod)
	}
	if currentContent == nil {
		currentContent = word.GetContent(currentMod)
	}

	if cmd == "r" {
		currentCMD = "r"
	} else if cmd == "gc" {
		currentCMD = "gc"
	} else if cmd == "ge" {
		currentCMD = "ge"
	} else if cmd == "h" {
		echoHelp()
		return
	} else if cmd == "c" {
		clear()
		return
	} else if cmd == "d" {
		clear()
		addContent(common.Pretend)
		return
	} else if cmd == "w" {
		currentMod = "w"
	} else if cmd == "m" {
		currentMod = "m"
	} else if cmd == "s" {
		currentMod = "s"
	}

	if currentCMD == "r" {
		addContent(currentContent.English)
		addContent(currentContent.Chinese)
	} else if currentCMD == "gc" {
		addContent(currentContent.English)
		if cmd == "t" {
			addContent(currentContent.Chinese)
		}
	} else if currentCMD == "ge" {
		if cmd == "t" {
			addContent(currentContent.English)
		}
		addContent(currentContent.Chinese)
	}
}